package com.scalar.chiptrack.finance.proformainvoice;

import com.scalar.chiptrack.operations.release.forms.TestReleaseForm;
import com.scalar.chiptrack.finance.proformainvoice.forms.ProformaInvoiceForm;
import com.scalar.chiptrack.finance.proformainvoice.forms.ProformaInvoiceSendMailForm;
import com.scalar.chiptrack.finance.proformainvoice.dao.ProformaInvoiceDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.PDFGenerator;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.ScalarException;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Calendar;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.HashMap;
import java.text.SimpleDateFormat;

import org.apache.struts.util.MessageResources;

/**
 * User: prasad
 * Date: Nov 9, 2007
 */
public class ProformaInvoiceHelper
{
    public static void resetProformaInvoiceForm( ProformaInvoiceForm form )
    {
        form.setSearchSalesOrderId( -1 );
        form.setSearchProcessstepId( -1 );
        form.setSearchSalesOrderNo( "" );
        form.setSearchInvoiceNo( "" );
        form.setSearchPONumber( "-1" );
        form.setSearchCustomerId( -1 );

        form.setInvoiceId   ( -1 );
        form.setInvoiceNo   ( "" );
        form.setInvoiceDate ( "" );
        form.setSalesOrderId( -1 );
        form.setBankName    ( "" );
        form.setAba         ( "" );
        form.setAcct        ( "" );
        form.setSwiftcode   ( "" );

        form.setLineItemList( null );
        form.setSalesOrder  ( null );
        form.setBankAddress ( null );       
    }

    public static void sendPrformaInvoiceNotifications( int invoiceId, String subject, String message, String to, String cc, String bcc, String mimeType, HttpServletRequest request, String sender, String fromEmailId)  throws ScalarException
    {
        String host                 = ConfigManager.getChipTracHost();
        String invoiceFile          = "";
        String[] mailAttachments    = null;
        String mailSubject          = null;


        try
        {
            ProformaInvoiceForm invoiceForm = new ProformaInvoiceForm();
            invoiceForm.setInvoiceId( invoiceId );

            ProformaInvoiceDAO.loadCompleteProformaInvoiceDetails( invoiceForm, invoiceId );

            if( mimeType.equalsIgnoreCase( "HTML" ) )
            {
                invoiceFile = getProformaInvoiceAsHtmlFile( host, invoiceForm, request );
            }
            else
            {
                invoiceFile = getProformaInvoiceAckPDFFile( host, invoiceForm );
            }

            mailSubject = "Proforma Invoice # " + invoiceForm.getInvoiceNo() + " from " +  sender ;

            to = StringUtils.removeDuplicateEmailIds ( to );

            if( subject == null || subject.trim().length() == 0 )
            {
                subject = mailSubject;
            }

            mailAttachments = new String[]{ invoiceFile };

            if( message != null && message.trim().length() > 0 )
            {
                message = message.replaceAll( "\n", "<br>" );
            }

            Mailer.send ( fromEmailId, to, cc, bcc, subject, message, mailAttachments, Mailer.CONTENT_TYPE_HTML, false );
        }
        catch ( Exception e )
        {
            e.printStackTrace();
            throw new ScalarException ( "Could not send Proforma Invoice notification mail" );
        }
    }


    public static String getProformaInvoiceAsHtmlFile( String host,  ProformaInvoiceForm invoiceForm, HttpServletRequest request )
	{
        String filePath             = null;
        String fileAsHtml           = null;
        String attachmentFileName   = null;
        FileWriter fWriter          = null;
        OutputStreamWriter out      = null;
        File ReleaseAttachment      = null;

        String dateInMonth  = "";
        String date         = "";
        String month        = "";
        String day          = "";
        Calendar cl	= Calendar.getInstance();
        SimpleDateFormat sdf = null;
        sdf = new SimpleDateFormat("MMM");
        dateInMonth = sdf.format( cl.getTime() );
        sdf = new SimpleDateFormat("MM");
        month = sdf.format( cl.getTime() );
        sdf = new SimpleDateFormat("dd");
        day = sdf.format( cl.getTime() );
        date = month + day;

        try
        {

            //ProformaInvoiceForm form = ( ProformaInvoiceForm ) invoiceForm;

            fileAsHtml = formatASHTMLforProformaInvoice( host, invoiceForm, request );

            attachmentFileName = "Proforma Invoice # " + invoiceForm.getInvoiceNo() + ".html";

            if( fileAsHtml == null )
            {
                return filePath;
            }

            // CREATE TEMPORARY ATTACHMENT FILE
            String mailingTempDir = ConfigManager.getMailerTempDir();
            File tempDir = new File (mailingTempDir).getCanonicalFile();

            tempDir.mkdir();

            //attachmentFileName = StringUtils.convertLowerCaseToUpperCase( attachmentFileName );

            ReleaseAttachment = new File( tempDir.getCanonicalPath(), attachmentFileName );
            ReleaseAttachment.deleteOnExit();

            if( ( ReleaseAttachment.exists() == true ) || ( ReleaseAttachment.createNewFile() == true ) )
            {
                out = new OutputStreamWriter( new FileOutputStream( ReleaseAttachment ), "UTF-8" );

                out.write( fileAsHtml );

                out.close();
                out = null;

                filePath = ReleaseAttachment.getAbsolutePath();
            }
        }
		catch( Exception e )
		{
			System.out.println( "Exception while creating Proforma Invoice html file");
			e.printStackTrace();
		}
		finally
		{
			if( fWriter != null )
			{
				try
				{
					fWriter.close();
					fWriter = null;
				}
				catch( IOException ignore ){}
			}
            if( fWriter != null )
			{
				try
				{
					fWriter.close();
					fWriter = null;
				}
				catch( IOException ignore ){}
			}
		}
		return filePath;
	}


    public static String formatASHTMLforProformaInvoice( String host, ProformaInvoiceForm form, HttpServletRequest request )
    {
        StringBuffer buf = new StringBuffer ( 2098 );
        SalesOrder salesOrder = form.getSalesOrder();

        buf.append ( "<HTML><HEAD><TITLE>Scalarsoft - ChipTrac</TITLE>" );
        buf.append ( "<LINK href='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/stylesheets/scalarsoft.css' type=text/css rel=stylesheet>" );
        buf.append ( "<style type='text/css'>" );
        buf.append ( "a { text-decoration : none}" );
        buf.append ( "</style>" );

        buf.append ( "</HEAD><BODY bgColor='#ffffff' leftMargin=0 topMargin=0 marginheight='0' marginwidth='0'>" );
        buf.append ( "<center><h2>Pro Forma Invoice</h2></center>" );
        buf.append ( "<Div1><table width='95%' cellspacing='0' cellpadding='0' border='0' align=center>" );
        buf.append ( " <tr>" );
        buf.append ( "<td width='34%' align='center'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/scalar_logo.jpg' height='72' width='180' border=0></td>" );
        buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
        Address clientAddress = salesOrder.getClientAddressAsObject ();
        // To display Client address
        buf.append ( "<td width='30%' align='center' class='NArialL'><br>" + salesOrder.getClientName () );
        buf.append ( "<br>" );
        buf.append ( salesOrder.getClientAddressAsHTML () );
        buf.append ( " </tr>" );

        buf.append ( "<tr><td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td></tr>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );

        String customerName = salesOrder.getCustomerName ();
        if ( salesOrder.getCustomerName ().equals ( salesOrder.getContactPerson () ) )
        {
            customerName = null;
        }

        buf.append ( " <tr>" );
        buf.append ( "<td height='100%'>" );//To set All three OrderedBy,BillTo and ShipTo address table same height
        buf.append ( "<table height='100%' border=1 width='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr height=20><td class='NArialL' bgcolor='#DEE1E2'>Bill To :</td></tr>" );
        buf.append ( "<tr height=20><td valign='top' class='NArialL' bgcolor='#FFFFEE'>" );
        buf.append ( "<table width='100%' class='NArialL' height=80 cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr><td valign='top'>" );


        if( salesOrder.getBillingAddressAsObject().getContactPerson() != null && salesOrder.getCustomerName().trim().length() !=0 )
        {
            if( ! salesOrder.getBillingAddressAsObject().getContactPerson().equals( salesOrder.getCustomerName() ) )
            {
                 buf.append(customerName + "<br>");
            }
        }

        buf.append (  salesOrder.getBillingAddressAsHTML() + "</td></tr>" );
        buf.append ( "</table>" );
        buf.append ( "</tr>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );

        buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );

        buf.append ( "<td height='100%'>" );
        buf.append ( "</td>" );

        buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );

        buf.append ( "<td height='100%'>" ); //To set All three BillTo and ShipTo address table same height
        buf.append ( "<table height='100%' border=1 width='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr height=20><td class='NArialL' bgcolor='#DEE1E2'>Ship To :</td></tr>" );
        buf.append ( "<tr height=20><td valign='top' class='NArialL' bgcolor='#FFFFEE'>" );
        buf.append ( "<table width='100%' class='NArialL' height=80 cellspacing='0' cellpadding='0'>" );

        //buf.append ( "<tr><td valign='top'>" + salesOrder.getCustomerName () + "<br>" );
        buf.append ( "<tr><td valign='top'>" + ( salesOrder.getOdm() != null && salesOrder.getOdm().length() > 0 ? salesOrder.getOdm () : salesOrder.getCustomerName () ) +"<br>" );

		buf.append (  salesOrder.getShippingAddressAsHTML() + "</td></tr>" );
        buf.append ( "</table>" );
        buf.append ( "</tr>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );

        buf.append ( "</tr>" );

        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td></tr>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td></tr>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );

        buf.append ( "<tr>" );
        buf.append ( "<td class='NArialL' height='20'>" );
        buf.append ( "<table width='100%' class='NArialL' border=1 bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr height=20><td bgcolor='#DEE1E2'>Sales Order#</td><td bgcolor='#DEE1E2'>Order Date</td></tr>" );
        buf.append ( "<tr height=20><td bgcolor='#FFFFEE'>" + salesOrder.getSalesOrderNo () + "&nbsp;</td><td bgcolor='#FFFFEE'>"+ ( (salesOrder.getBookingdateAsString () == null || salesOrder.getBookingdateAsString ().equals("null")) ? "" : salesOrder.getBookingdateAsString ()) + " &nbsp;</td></tr>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );
        buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
        buf.append ( "<td class='NArialL' height='20'>" );
        buf.append ( "<table width='100%' class='NArialL' border=1 bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr height=20><td bgcolor='#DEE1E2'>Invoice # </td><td bgcolor='#DEE1E2'>Invoice Date </td></tr>" );
        buf.append ( "<tr height=20><td bgcolor='#FFFFEE'>" + form.getInvoiceNo() + "&nbsp;</td><td bgcolor='#FFFFEE'>" + form.getInvoiceDate() + "&nbsp;</td></tr>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );
        buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
        buf.append ( "<td class='NArialL' height='20'>" );
        buf.append ( "<table width='100%' class='NArialL' border=1 bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr height=20><td  bgcolor='#DEE1E2'>Sales Person</td><td bgcolor='#DEE1E2'>Customer PO#</td><td bgcolor='#DEE1E2'>Del Terms</td><td bgcolor='#DEE1E2'>Pay Terms</td></tr>" );
        buf.append ( "<tr height=20><td bgcolor='#FFFFEE'>" + salesOrder.getSalesPerson () + "&nbsp;</td><td bgcolor='#FFFFEE'>" + salesOrder.getCustomerPO () + "&nbsp;</td><td bgcolor='#FFFFEE'>" + salesOrder.getDeliveryTerms () + "&nbsp;</td><td bgcolor='#FFFFEE'>" + ( salesOrder.getShippingTerms ().trim ().equals ( "-1" ) ? "" : salesOrder.getShippingTerms () ) + "&nbsp;</td></tR>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );
        buf.append ( "</tr>" );

        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
        buf.append ( "<tr><td colspan='5'>" );
        buf.append ( "<table width='100%' border=1 bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr height=30>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align=center>PO Line#</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>UM</td>" );

        String mfgPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.mfgPartNumber" );
        if ( mfgPartNumberLabel == null )
        {
            mfgPartNumberLabel = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
        }

        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>" + mfgPartNumberLabel + "</td>" );


        String customerPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.customerPartNumber" );
        if ( customerPartNumberLabel == null )
        {
            customerPartNumberLabel = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
        }

        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>" + customerPartNumberLabel + "</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Product Description</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Requested<br>Dock Date</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Scheduled<br>Ship Date</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Revised<br>Ship Date</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Taxable</td>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align=center>Ship Qty</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Unit<br>Price</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Extended<br>Price</td>" );

        buf.append ( "</tr>" );

        ArrayList lineItemList              = form.getLineItemList();
        ProformaInvoiceLineItem lineItem    = null;
        double grandTotal = 0d;
        for ( int i = 0; i < lineItemList.size (); i++ )
        {
            lineItem = ( ProformaInvoiceLineItem ) lineItemList.get ( i );
            if( lineItem.isSelected() )
            {
                buf.append ( "<tr height=20>" );
                buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center>" +  lineItem.getPoLineItemNo () + "&nbsp;</td>" );
                buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center>ea</td>" );
                buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center nowrap>" + ( ( lineItem.getManufacturingPartNo() == null || lineItem.getManufacturingPartNo().equals( "null" ) ) ? "" : lineItem.getManufacturingPartNo () )  + "&nbsp;</td>" );
                buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center nowrap>" + ( ( lineItem.getCustomerPartNo() == null || lineItem.getCustomerPartNo().equals( "null" ) ) ? "" : lineItem.getCustomerPartNo() ) + "&nbsp;</td>" );
                buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' wrap>" + ( ( lineItem.getLineItemDescription() == null || lineItem.getLineItemDescription().equals( "null" ) ) ? "" : lineItem.getLineItemDescription() ) + "&nbsp;</td>" );
                buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center>" + ( ( lineItem.getRequestDate() == null || lineItem.getRequestDate().equals( "null" ) ) ? "" : lineItem.getRequestDate() ) + "&nbsp;</td>" );
                buf.append ( "<td  bgcolor='#FFFFEE'  class='NArialL' align=center>" + ( ( lineItem.getScheduleDate() == null || lineItem.getScheduleDate().equals( "null" ) ) ? "" : lineItem.getScheduleDate() ) + "&nbsp;</td>" );
                buf.append ( "<td  bgcolor='#FFFFEE'  class='NArialL' align=center>" + ( ( lineItem.getRevisedDate() == null || lineItem.getRevisedDate().equals( "null" ) ) ? "" : lineItem.getRevisedDate() ) + "&nbsp;</td>" );
                buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center>" + ( ( lineItem.getIsTaxableAsString() == null || lineItem.getIsTaxableAsString().equals( "null" ) ) ? "" : lineItem.getIsTaxableAsString() ) + "&nbsp;</td>" );
                buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getQtyPulledStr() + "&nbsp;</td>" );
                buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center>" + ( ( lineItem.getUnitPriceAsString() == null || lineItem.getUnitPriceAsString().equals( "null" ) ) ? "" : lineItem.getUnitPriceAsString() ) + "&nbsp;</td>" );
                buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=right>" + ( ( lineItem.getAmountAsString() == null || lineItem.getAmountAsString().equals( "null" ) ) ? "" : lineItem.getAmountAsString() ) + "&nbsp;</td>" );
                buf.append ( "</tr>" );
                grandTotal += lineItem.getAmountAsDouble();
            }
        }
        buf.append ( "</table>" );
        buf.append ( "</td></tr>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );

        buf.append( "<tr><td colspan=5 bgcolor='#DEE1E2' align='right' valign=top><font class='NArialL'>Grand Total:&nbsp;" + StringUtils.formatAmount(grandTotal, "$###,###.###") + "&nbsp;");
        buf.append( "</font></td></tr>" );
        
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
        buf.append ( "<tr>" );
        buf.append ( "<td colspan='5'>" );
        buf.append ( "<table width='100%' border='0'>" );
        buf.append ( "<tr>" );
        buf.append ( "<td width='70%' class='NArialL' align='left'>" );
        buf.append ( "<table width='45%' class='NArialL' border='1' cellspacing='0' bordercolor='#000000'>" );
        buf.append ( "<tr height=30>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL'> Banking Information :</td>" );
        buf.append ( "</tr>" );
        buf.append ( "<tr>" );
        buf.append ( "<td bgcolor='#FFFFEE' class='NArialL'>" );
        buf.append ( form.getBankName() );
        buf.append ( "<br>" );
        buf.append ( form.getBankAddress().getAddressAsHTML() );
        buf.append ( form.getBankDetailsAsString() );
        buf.append ( "</td>" );
        buf.append ( "</tr>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );
        buf.append ( "<td width='30%'>&nbsp;</td>" );
        buf.append ( "</tr>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );
        buf.append ( "</tr>" );
        buf.append ( "</table>");
        buf.append("</div1>");
        buf.append ( "<div style='page-break-after: always;'>&nbsp;</div><table width='100%' cellspacing='5' cellpadding='0' border=0 align=center>" );
        buf.append ( "<TR>" );
        buf.append ( "<TD width='100%' colspan='3' class='viewdata1'>&nbsp;</TD>" );
        buf.append ( "</TR>" );
        buf.append( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=25></td></tR>" );
        buf.append ( "<tr><td colspan='5'>" );
        buf.append ( "<table border='0' width='100%' >" );
        buf.append ( "<td width='10%' class='NArialL' align=center>Signature:</td>" );
        buf.append ( "<td width='50%' class='NArialL' align=left ><hr></td>" );
        buf.append ( "<td width='5%' class='NArialL' align=center>&nbsp;</td>" );
        buf.append ( "<td width='10%' class='NArialL' align=right>Date:</td>" );
        buf.append ( "<td width='20%' class='NArialL' align=center><hr></td>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );
        buf.append ( "</tr>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=25></td></tR>" );
        buf.append ( "</table>" );
        buf.append ( "</body></html>" );

        return buf.toString ();

    }

    public static String getProformaInvoiceAckPDFFile ( String host, ProformaInvoiceForm invoiceForm ) throws ScalarException
    {
        String fileXMLPath  = null;
        String filePDFPath  = null;
        String saAsXML      = null;
        String xmlFileName  = null;
        String xsltFileName = null;
        String saAttachmentPDFFileName = null;
        OutputStreamWriter out = null;

        String dateInMonth  = "";
        String date         = "";
        String month        = "";
        String day          = "";
        Calendar cl	= Calendar.getInstance();
        SimpleDateFormat sdf = null;
        sdf = new SimpleDateFormat("MMM");
        dateInMonth = sdf.format( cl.getTime() );
        sdf = new SimpleDateFormat("MM");
        month = sdf.format( cl.getTime() );
        sdf = new SimpleDateFormat("dd");
        day = sdf.format( cl.getTime() );
        date = month + day;

        //ProformaInvoiceForm form = ( ProformaInvoiceForm ) invoiceForm;
        saAsXML = formatAsXMLForProformaInvoice ( host, invoiceForm );

        xmlFileName = "Proforma Invoice #" + invoiceForm.getInvoiceNo() + ".xml";

        saAttachmentPDFFileName = "Proforma Invoice #" + invoiceForm.getInvoiceNo() + ".pdf";


        if ( saAsXML == null || saAsXML.trim().length() == 0 )
        {
           return fileXMLPath;
        }

        FileWriter fWriter = null;
        File saPDFAttachment = null;
        File saXML = null;

        try
        {
            // CREATE TEMPORARY ATTACHMENT FILE
            String mailingTempDir = ConfigManager.getMailerTempDir ();
            File tempDir = new File ( mailingTempDir ).getCanonicalFile ();
            tempDir.mkdir ();

            //saAttachmentPDFFileName = StringUtils.convertLowerCaseToUpperCase( saAttachmentPDFFileName );

            xsltFileName = ConfigManager.getProFormaInvoiceXml2PdfXslFile();


            saXML = new File ( tempDir.getCanonicalPath (), xmlFileName );
            saXML.deleteOnExit ();

            saPDFAttachment = new File ( tempDir.getCanonicalPath (), saAttachmentPDFFileName );
            saPDFAttachment.deleteOnExit ();

            if ( ( saXML.exists () == true ) || ( saXML.createNewFile () == true ) )
            {
                out = new OutputStreamWriter( new FileOutputStream( saXML ), "UTF-8" );

                out.write ( saAsXML );
                out.close ();
                out = null;

                fileXMLPath = saXML.getCanonicalPath().toUpperCase();
                filePDFPath = saPDFAttachment.getCanonicalPath().toUpperCase();

                PDFGenerator.convertXML2PDF ( fileXMLPath, xsltFileName, filePDFPath );
            }
        }
        catch ( Exception e )
        {
            System.out.println ( "Exception while creating Proforma invoice Build Ack PDF file" );
            e.printStackTrace ();
        }
        finally
        {
            if ( fWriter != null )
            {
                try
                {
                    fWriter.close ();
                    fWriter = null;
                }
                catch ( IOException ignore ){}
            }
            if ( out != null )
            {
                try
                {
                    out.close ();
                    out = null;
                }
                catch ( IOException ignore ){}
            }
        }

       return filePDFPath;
    }

    public static String formatAsXMLForProformaInvoice ( String host, ProformaInvoiceForm form ) throws ScalarException
    {
        StringBuffer buf = new StringBuffer ( 2098 );

        SalesOrder salesOrder = form.getSalesOrder();

        buf.append ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n" );
        buf.append ( "<proFormaInvoice>" + "\n" );
        buf.append ( "<logo>" + ConfigManager.getChipTracImagesDir () + ConfigManager.getScalarLogo () + "</logo>" + "\n" );
        buf.append ( "<selfAddress>" + "\n" );
        //To get client Address
        buf.append ( "<name><![CDATA[" + salesOrder.getClientName () + "]]></name>" + "\n" );
        Address clientAddress = salesOrder.getClientAddressAsObject ();

        buf.append ( "<address1><![CDATA[" + clientAddress.getAddress1 () + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + clientAddress.getAddress2 () + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + clientAddress.getAddress3 () + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + clientAddress.getAddress4 () + "]]></address4>" + "\n" );
        StringBuffer cityStateZip = new StringBuffer ( "" );

        if ( !clientAddress.getCity ().equals ( "" ) ) cityStateZip.append ( clientAddress.getCity () + ", " );
        if ( !clientAddress.getState ().equals ( "" ) ) cityStateZip.append ( clientAddress.getState () + " - " );
        if ( !clientAddress.getZipCode ().equals ( "" ) ) cityStateZip.append ( clientAddress.getZipCode () + ", " );
        cityStateZip.append ( clientAddress.getCountry () );

        buf.append ( "<cityStateZip><![CDATA[" + cityStateZip + "]]></cityStateZip>" + "\n" );

        StringBuffer phFax = new StringBuffer ();
        if ( !clientAddress.getPhoneNumber ().equals ( "" ) ) phFax.append ( "Ph." + clientAddress.getPhoneNumber () + ", " );
        if ( !clientAddress.getFaxNumber ().equals ( "" ) ) phFax.append ( "Fax." + clientAddress.getFaxNumber () );

        buf.append ( "<phoneFax><![CDATA[" + phFax + "]]></phoneFax>" + "\n" );
        buf.append ( "</selfAddress>" + "\n" );

        Address address = salesOrder.getBillingAddressAsObject ();

        String customerName = salesOrder.getCustomerName ();
        if ( salesOrder.getCustomerName ().equals ( salesOrder.getContactPerson () ) )
        {
            customerName = "";
        }

        buf.append ( "<billToAddress>" + "\n" );

        if( salesOrder.getBillingAddressAsObject().getContactPerson() != null && salesOrder.getCustomerName().trim().length() !=0 )
        {
            if( ! salesOrder.getBillingAddressAsObject().getContactPerson().equals( salesOrder.getCustomerName() ) )
            {
                buf.append ( "<name><![CDATA[" + customerName + "]]></name>" + "\n" );
            }
        }
        buf.append ( "<contactPerson><![CDATA[" + address.getContactPerson () + "]]></contactPerson>" + "\n" );
        buf.append ( "<address1><![CDATA[" + address.getAddress1 () + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + address.getAddress2 () + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + address.getAddress3 () + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + address.getAddress4 () + "]]></address4>" + "\n" );

        buf.append ( "<city><![CDATA["+ address.getCity () + "]]></city>" + "\n" );
        buf.append ( "<stateZipCountry><![CDATA[" );
        if(address.getState ()!=null && !(address.getState ().equals("")))
        {
            buf.append(address.getState ());
        }
        if(address.getZipCode()!=null && !(address.getZipCode().equals("")))
        {
            if(address.getState ()!=null && !(address.getState ().equals("")))
            {
                buf.append(" - ");
            }
            buf.append(address.getZipCode());
        }
        if(address.getCountry ()!=null && !(address.getCountry ().equals("")))
        {
            if((address.getZipCode()!=null && !(address.getZipCode().equals("")))||(address.getState ()!=null && !(address.getState ().equals(""))))
            {
                buf.append(", ");
            }
            buf.append(address.getCountry ());
        }
        buf.append ( "]]></stateZipCountry>" + "\n" );

         buf.append ( "<phone><![CDATA[" + ( ( ( address.getPhoneNumber () != null ) && ( address.getPhoneNumber() .trim().length() > 0) )? "Tel:"+address.getPhoneNumber () : "" ) + "]]></phone>" + "\n" );
        buf.append ( "<cell><![CDATA[" + ( ( ( address.getCellNumber () != null ) && ( address.getCellNumber() .trim() .length() > 0 ) )? "Cell No:"+ address.getCellNumber () : "") + "]]></cell>" + "\n" );
        buf.append ( "<fax><![CDATA[" + ( ( ( address.getFaxNumber () != null ) && (address.getFaxNumber() .trim() .length() > 0 ) ) ? "Fax:"+ address.getFaxNumber () : "" ) + "]]></fax>" + "\n" );
        buf.append ( "<email><![CDATA[" + ( ( ( address.getEmail () != null ) && (address.getEmail() .trim().length() > 0 ) ) ? "Email:"+ address.getEmail () : "") + "]]></email>" + "\n" );
        buf.append ( "</billToAddress>" + "\n" );

        address = salesOrder.getShippingAddressAsObject ();

        buf.append ( "<shipToAddress>" + "\n" );

        String shipersName = salesOrder.getOdm() != null && salesOrder.getOdm().length() > 0 ? salesOrder.getOdm() : salesOrder.getCustomerName () ;
        buf.append ( "<name><![CDATA[" + shipersName + "]]></name>" + "\n" );

        buf.append ( "<contactPerson><![CDATA[" + address.getContactPerson () + "]]></contactPerson>" + "\n" );
        buf.append ( "<address1><![CDATA[" + address.getAddress1 () + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + address.getAddress2 () + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + address.getAddress3 () + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + address.getAddress4 () + "]]></address4>" + "\n" );

        buf.append ( "<city><![CDATA["+ address.getCity () + "]]></city>" + "\n" );
        buf.append ( "<stateZipCountry><![CDATA[" );
        if(address.getState ()!=null && !(address.getState ().equals("")))
        {
            buf.append(address.getState ());
        }
        if(address.getZipCode()!=null && !(address.getZipCode().equals("")))
        {
            if(address.getState ()!=null && !(address.getState ().equals("")))
            {
                buf.append(" - ");
            }
            buf.append(address.getZipCode());
        }
        if(address.getCountry ()!=null && !(address.getCountry ().equals("")))
        {
            if((address.getZipCode()!=null && !(address.getZipCode().equals("")))||(address.getState ()!=null && !(address.getState ().equals(""))))
            {
                buf.append(", ");
            }
            buf.append(address.getCountry ());
        }
        buf.append ( "]]></stateZipCountry>" + "\n" );
         buf.append ( "<phone><![CDATA[" + ( ( ( address.getPhoneNumber () != null ) && ( address.getPhoneNumber() .trim().length() > 0) )? "Tel:"+address.getPhoneNumber () : "" ) + "]]></phone>" + "\n" );
        buf.append ( "<cell><![CDATA[" + ( ( ( address.getCellNumber () != null ) && ( address.getCellNumber() .trim() .length() > 0 ) )? "Cell No:"+ address.getCellNumber () : "") + "]]></cell>" + "\n" );
        buf.append ( "<fax><![CDATA[" + ( ( ( address.getFaxNumber () != null ) && (address.getFaxNumber() .trim() .length() > 0 ) ) ? "Fax:"+ address.getFaxNumber () : "" ) + "]]></fax>" + "\n" );
        buf.append ( "<email><![CDATA[" + ( ( ( address.getEmail () != null ) && (address.getEmail() .trim().length() > 0 ) ) ? "Email:"+ address.getEmail () : "") + "]]></email>" + "\n" );
        buf.append ( "</shipToAddress>" + "\n" );

        buf.append ( "<information>" + "\n" );
        buf.append ( "<customerPO><![CDATA[" + salesOrder.getCustomerPO () + "]]></customerPO>" + "\n" );
        buf.append ( "<salesOrder><![CDATA[" + salesOrder.getSalesOrderNo () + "]]></salesOrder>" + "\n" );
        buf.append ( "<orderDate><![CDATA[" + salesOrder.getBookingdateAsString () + "]]></orderDate>" + "\n" );
        buf.append ( "<shipVia><![CDATA[" + salesOrder.getShippingMethod () + "]]></shipVia>" + "\n" );
        buf.append ( "<salesPerson><![CDATA[" + salesOrder.getSalesPerson () + "]]></salesPerson>" + "\n" );
        buf.append ( "<regionalRep><![CDATA[" + salesOrder.getRegionalRep () + "]]></regionalRep>" + "\n" );
        buf.append ( "<delTerms><![CDATA[" + salesOrder.getDeliveryTerms () + "]]></delTerms>" + "\n" );
        buf.append ( "<payTerms><![CDATA[" + ( salesOrder.getShippingTerms ().trim ().equals ( "-1" ) ? "" : salesOrder.getShippingTerms () ) + "]]></payTerms>" + "\n" );
        buf.append ( "<invoiceNo><![CDATA[" + form.getInvoiceNo() + "]]></invoiceNo>" + "\n" );
        buf.append ( "<invoiceDate><![CDATA[" + form.getInvoiceDate() + "]]></invoiceDate>" + "\n" );
        buf.append ( "</information>" + "\n" );

        buf.append ( "<lineItems>" + "\n" );
        String mfgPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.mfgPartNumber" );
        if ( mfgPartNumberLabel == null )
        {
            mfgPartNumberLabel = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
        }
        String customerPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.customerPartNumber" );
        if ( customerPartNumberLabel == null )
        {
            customerPartNumberLabel = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
        }

        buf.append ( "<labelMfgPartNumber><![CDATA[" + mfgPartNumberLabel + "]]></labelMfgPartNumber>" );
        buf.append ( "<labelCustPartNumber><![CDATA[" + customerPartNumberLabel + "]]></labelCustPartNumber>" );

        ArrayList lineItemList              = form.getLineItemList();
        ProformaInvoiceLineItem lineItem    = null;
        double lineItemTotalAmount = 0d;
        for ( int i = 0; i < lineItemList.size (); i++ )
        {
            lineItem = ( ProformaInvoiceLineItem ) lineItemList.get ( i );
            if( lineItem.isSelected() )
            {
                buf.append ( "<lineItem>" + "\n" );
                buf.append ( "<poLineItem><![CDATA[" + lineItem.getPoLineItemNo () + "]]></poLineItem>" + "\n" );
                buf.append ( "<um><![CDATA[" + "ea" + "]]></um>" + "\n" );
                buf.append ( "<mfgPartNumber><![CDATA[" + ( ( lineItem.getManufacturingPartNo() != null && lineItem.getManufacturingPartNo().trim().length() > 0 ) ?  lineItem.getManufacturingPartNo() : "") + "]]></mfgPartNumber>" + "\n" );
                buf.append ( "<customerPartNumber><![CDATA[" + ( ( lineItem.getCustomerPartNo() != null && lineItem.getCustomerPartNo().trim().length() > 0 ) ?  lineItem.getCustomerPartNo() : "" ) + "]]></customerPartNumber>" + "\n" );
                buf.append ( "<description><![CDATA[" + ( ( lineItem.getDescription() != null && lineItem.getDescription().trim().length() > 0 ) ?  lineItem.getDescription() : "" ) + "]]></description>" + "\n" );
                buf.append ( "<requestDate><![CDATA[" + ( ( lineItem.getRequestDate() != null && lineItem.getRequestDate().trim().length() > 0 ) ?  lineItem.getRequestDate() : "" ) + "]]></requestDate>" + "\n" );
                buf.append ( "<scheduleDate><![CDATA[" + ( ( lineItem.getScheduleDate() != null && lineItem.getScheduleDate().trim().length() > 0 ) ?  lineItem.getScheduleDate() : "" ) + "]]></scheduleDate>" + "\n" );
                buf.append ( "<revisedShipDate><![CDATA[" + ( ( lineItem.getRevisedDate() != null && lineItem.getRevisedDate().trim().length() > 0 ) ?  lineItem.getRevisedDate() : "" ) + "]]></revisedShipDate>" + "\n" );
                buf.append ( "<taxable><![CDATA[" + ( ( lineItem.getIsTaxableAsString() != null && lineItem.getIsTaxableAsString().trim().length() > 0 ) ?  lineItem.getIsTaxableAsString() : "" ) + "]]></taxable>" + "\n" );
                buf.append ( "<reqQty><![CDATA[" + lineItem.getQtyPulledStr() + "]]></reqQty>" + "\n" );
                buf.append ( "<unitPrice><![CDATA[" + lineItem.getUnitPriceAsString () + "]]></unitPrice>" + "\n" );
                buf.append ( "<extendedPrice><![CDATA[" + lineItem.getAmountAsString () + "]]></extendedPrice>" + "\n" );
                buf.append ( "</lineItem>" + "\n" );
                lineItemTotalAmount += lineItem.getAmountAsDouble();
            }
        }
        buf.append ( "</lineItems>" + "\n" );

        buf.append ( "<total><![CDATA[" + StringUtils.formatAmount( lineItemTotalAmount, "$###,###.###" ) + "]]></total>" );

        Address bankInfo = form.getBankAddress();

        buf.append ( "<bankInformation>" );
        buf.append ( "<bankName><![CDATA[" + ( ( form.getBankName() == null || form.getBankName().equals("")) ? "" : form.getBankName() ) + "]]></bankName>" + "\n" );
        buf.append ( "<address1><![CDATA[" + ( ( bankInfo.getAddress1() == null || bankInfo.getAddress1().equals("")) ? "" : bankInfo.getAddress1() ) + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + ( ( bankInfo.getAddress2() == null || bankInfo.getAddress2().equals("")) ? "" : bankInfo.getAddress2() ) + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + ( ( bankInfo.getAddress3() == null || bankInfo.getAddress3().equals("")) ? "" : bankInfo.getAddress3() ) + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + ( ( bankInfo.getAddress4() == null || bankInfo.getAddress4().equals("")) ? "" : bankInfo.getAddress4() ) + "]]></address4>" + "\n" );
        buf.append ( "<city><![CDATA[" + ( ( bankInfo.getCity() == null || bankInfo.getCity().equals("")) ? "" : bankInfo.getCity() ) + "]]></city>" + "\n" );
        //buf.append ( "<state><![CDATA[" + ( ( bankInfo.getState() == null || bankInfo.getState().equals("")) ? "" : bankInfo.getState()+ " - ")  + ( (bankInfo.getZipCode() == null || bankInfo.getZipCode().equals("")) ? "" : bankInfo.getZipCode()+ ", ")  + ( (bankInfo.getCountry() == null || bankInfo.getCountry().equals("")) ? "" : bankInfo.getCountry()) + "]]></state>" + "\n" );
        buf.append ( "<state><![CDATA[" + ( ( bankInfo.getState() == null || bankInfo.getState().equals( "" ) ) ? "" : bankInfo.getState() ) + "]]></state>" + "\n" );
        buf.append ( "<zipcode><![CDATA[" + ( ( bankInfo.getZipCode() == null || bankInfo.getZipCode().equals("")) ? "" : bankInfo.getZipCode() ) + "]]></zipcode>" + "\n" );
        buf.append ( "<country><![CDATA[" + ( ( bankInfo.getCountry() == null || bankInfo.getCountry().equals("")) ? "" : bankInfo.getCountry() ) + "]]></country>" + "\n" );
        buf.append ( "<aba><![CDATA[" + ( ( form.getAba() == null || form.getAba().equals("")) ? "" : form.getAba() ) + "]]></aba>" + "\n" );
        buf.append ( "<account><![CDATA[" + ( ( form.getAcct() == null || form.getAcct().equals("")) ? "" : form.getAcct() ) + "]]></account>" + "\n" );
        buf.append ( "<swiftcode><![CDATA[" + ( ( form.getSwiftcode() == null || form.getSwiftcode().equals("")) ? "" : form.getSwiftcode() ) + "]]></swiftcode>" + "\n" );
        buf.append ( "</bankInformation>" + "\n" );

        /*buf.append ( "<total><![CDATA[" + salesOrder.getFinalSubTotalAsString () + "]]></total>" + "\n" );
        buf.append ( "<salesTax><![CDATA[" + salesOrder.getSalesTaxAsString () + "]]></salesTax>" + "\n" );
        buf.append ( "<freight><![CDATA[" + salesOrder.getFrieghtAsString () + "]]></freight>" + "\n" );
        buf.append ( "<misc name=\"" + salesOrder.getMiscName () + "\"><![CDATA[" + salesOrder.getMiscAsString () + "]]></misc>" + "\n" );
        buf.append ( "<balanceDue><![CDATA[" + salesOrder.getFinalOrderTotalAsString () + "]]></balanceDue>" + "\n" );*/

        buf.append ( "</proFormaInvoice>" + "\n" );

        return buf.toString ();
    }


    public static void resetProformaInvoiceMailForm( ProformaInvoiceSendMailForm form )
    {
        form.setInvoiceId( -1 );
        form.setInvoiceNo( null );
        form.setFromUser( null );
        form.setMessage( null );
        //form.setAttachMIMEType( null );
        form.setFromNotification( false );
        form.setProcessType( null );
        form.setToRecipientsEmailsList( null );
        form.setCcRecipientsEmailsList( null );
        form.setBccRecipientsEmailsList( null );
        form.setDivCcDisplayStyle( null );
        form.setDivBccDisplayStyle( null );
    }

}
